import { createStore, combineReducers,applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'
import { routerReducer } from 'react-router-redux'

//设置默认状态

function sessionStoragePut(key,value){
    //将对象转化成json字符串，存入sessionStorage
    localStorage.setItem(key, JSON.stringify(value));
}
function sessionStorageGet(key,isRemove){
    //从sessionStorage中取出json字符串，然后将json字符串转化成对象,并返回.
    var result=JSON.parse(localStorage.getItem(key));
    if(isRemove){
        localStorage.removeItem(key);
    }
    return result;
}

  let user={
    user_logined:false,
    userId:0,
    userTel:''
  }
  let myuser;
  // 刷新的时候 如果缓存中有用户信息 覆盖上面的
  if(!!localStorage.getItem('user')){
    myuser = sessionStorageGet('user');
  }else{
    myuser = sessionStoragePut('user',user);
  }

module.exports = function(initialState = {user:myuser}) {
  const store = createStore(
    combineReducers({
      ...rootReducer,
      routing: routerReducer,
    }),
    initialState,
    applyMiddleware(thunkMiddleware),
  )

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers').default
      store.replaceReducer(nextReducer)
    })
  }

  return store
}
